package com.heima.wemedia.service.impl;

import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.index.qual.SameLen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinioService minioService;

    /**
     * 根据url查询素材信息
     * */
    @Override
    public WmMaterial getByUrl(String url) {
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getUrl, url);
        return this.getOne(queryWrapper);
    }

    @Override
    public String uploadPicture(MultipartFile file) {
        // 上传到minio
        String url = uploadToMinio(file);
        // 保存到数据库
        saveToDB(url);
        return url;
    }

    private String uploadToMinio(MultipartFile file) {
        // 上传之前重命名，防止同名覆盖
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.indexOf(".") + 1);
        String filename = UUID.randomUUID().toString() + "." + suffix;
        // 上传到minio
        String url = "";
        try {
            url = minioService.uploadImgFile("", filename, file.getInputStream());
        } catch (IOException e) {
            log.error("minio上传失败：{}", ExceptionUtil.getStackTrace(e));
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }
        return url;
    }

    private void saveToDB(String url) {
        WmMaterial toBeInsert = new WmMaterial();
        toBeInsert.setCreatedTime(new Date());
        toBeInsert.setUrl(url);
        toBeInsert.setType(0);//TODO 枚举
        toBeInsert.setIsCollection(false);
        toBeInsert.setUserId(UserThreadLocalUtils.getUserId());
        this.save(toBeInsert);
    }

    @Override
    public PageResult<WmMaterial> pageQuery(WmMaterialDto dto) {
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        // 设置查询条件
        queryWrapper.eq(dto.getIsCollection()!=null, WmMaterial::getIsCollection, dto.getIsCollection());
        // 一定要注意：只能查询自己的素材
        queryWrapper.eq(WmMaterial::getUserId, UserThreadLocalUtils.getUserId());
        // 分页条件
        Page<WmMaterial> ipage = new Page<>(dto.getPage(), dto.getSize());
        // 查询
        Page<WmMaterial> pageResponse = this.page(ipage, queryWrapper);
        return new PageResult<>(dto.getPage(), dto.getSize(),pageResponse.getTotal(), pageResponse.getRecords());
    }
}
